package message

import (
	"context"
	"go_final/mxshop_api/userop_web/api"
	"go_final/mxshop_api/userop_web/forms"
	"go_final/mxshop_api/userop_web/global"
	messagepb "go_final/mxshop_api/userop_web/proto/protofile/message"
	"net/http"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

func Create(c *gin.Context) {
	createMessageForm := forms.CreateMessageForm{}
	err := c.ShouldBind(&createMessageForm)
	if err != nil {
		api.HandleValidateError(c, err)
		return
	}

	userID, _ := c.Get("userId")
	res, err := global.MessageClient.CreateMessage(context.Background(), &messagepb.MessageRequest{
		UserId:      int32(userID.(uint)),
		MessageType: int32(createMessageForm.MessageType),
		Subject:     createMessageForm.Subject,
		Message:     createMessageForm.Message,
		File:        createMessageForm.File,
	})

	if err != nil {
		zap.S().Error("invoke CreateMessage failed: ", err.Error())
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message_id": res.Id,
	})
}

func List(c *gin.Context) {
	userID, _ := c.Get("userId")

	res, err := global.MessageClient.MessageList(context.Background(), &messagepb.MessageRequest{
		UserId: int32(userID.(uint)),
	})

	if err != nil {
		zap.S().Error("invoke MessageList failed: ", err.Error())
		api.HandleGrpcError2Http(err, c)
		return
	}

	c.JSON(http.StatusOK, res)
}
